package pers.ljf.escloud.controller;

import com.aliyun.oss.OSS;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import pers.ljf.escloud.common.dto.AppLoginUserInfo;
import pers.ljf.escloud.common.utils.StringUtils;
import pers.ljf.escloud.common.utils.UserInfoUtils;

@Controller
public class BaseController implements FIleController {

    public static AppLoginUserInfo getUserEntity() {
        return UserInfoUtils.get();
    }

    protected static Long getUserId() {
        return getUserEntity().getUserId();
    }

    @Override
    public OSS getClient() {
        return UserInfoUtils.get().getOssClient();
    }


    @Override
    public String getFullPath(String path) {
        String fullPath = StringUtils.removeFirstSeparator(StringUtils.getFullPath(UserInfoUtils.get().getBasePath(), path));
        return fullPath;
    }

    /**
     * 拼接前端path与basePath为objName
     * @param path 不可为空
     * @param firstSeparator 返回值是否需要以"/"开头
     * @return
     */
    public String getFullPath(String path, Boolean firstSeparator) {
        String basePath = UserInfoUtils.get().getBasePath();
        Assert.isTrue(StringUtils.isNotNullOrEmpty(basePath), "basePath为空");
        Assert.isTrue(StringUtils.isNotNullOrEmpty(path),"path为空");
        //保证path不以"/"开头
        path = path.charAt(0) == '/' ? path.substring(1) : path;
        String fullPath;
        //核心：拼接路径，拼接前加分隔符
        if (StringUtils.isNotNullOrEmpty(path)) {
            basePath = basePath + "/";
        }
        fullPath = basePath + path;
        //处理basePath的firstSeparator
        if (!firstSeparator && fullPath.charAt(0) == '/') {
            fullPath = fullPath.substring(1);
        }
        if (firstSeparator && fullPath.charAt(0) != '/') {
            fullPath = "/" + fullPath;
        }
        return fullPath;
    }
    //basePath: department.getFullPathName()
    public String getBasePath() {
        return UserInfoUtils.get().getBasePath();
    }

    @Override
    public String getBucketName() {
        return UserInfoUtils.get().getBucketName();
    }

    @Override
    public String getToken() {
        return UserInfoUtils.get().getToken();
    }
}
